/****************
 *@description: 采购管理 采购列表  procurement/list/index
 *@author: Xhd
 *@date: 2023-07-13 13:15:41
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import TheTable from '@/components/TheTable';
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import store from "@/store/store";
import { exportSheetTable } from '@/utils/exportTable.js';
import {apiGetstockPurchasePage, apiStockPurchaseExport} from "@/request/procurement";

class Procurement extends Component {
  constructor(props){
    super(props);
    this.queryFormRef = React.createRef()
    this.state = {
      form_show: true,
      searchOption: [
        { field: 'goodsName', label: '物料名称', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'code', label: '采购单号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'libraryId', label: '仓库', placeholder: '请选择', required: false, rules: [], type: 'Select',txt: 'name', value: 'id', options: [] },
        { field: 'supplierName', label: '供应商', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'skuNo', label: '物料ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'status', label: '订单状态', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{label:"未完成",value:"0"},{label:"处理中",value:"1"},{label:"已完成",value:"2"}] },
      ],
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          render:(text,record,index) =>{
            return((this.state.pageData.pageNo - 1)*(this.state.pageData.pageSize) + (index + 1));
          }
        },
        {
          title: "采购单号",
          dataIndex: "code",
          key: "code",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "外部单号",
          dataIndex: "code",
          key: "code",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "供应商",
          dataIndex: "supplierName",
          key: "supplierName",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "仓库",
          dataIndex: "libraryName",
          key: "libraryName",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "采购数量",
          dataIndex: "serviceShowFile",
          key: "serviceShowFile",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "创建人",
          dataIndex: "memberName",
          key: "memberName",
          render: (text, render) => {
              return text
          }
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "订单状态",
          dataIndex: "status",
          key: "status",
          render: (text, render) => {
            let status = ""
            switch (text) {
              case 0:
                status =<div style={{color:"red"}} >未完成</div>
                break;
              case 1:
                status =<div style={{color:"orange"}} >处理中</div>
                break;
              case 2:
                status ="已完成"
                break;
              default:
                break;
            }
            return status
          }
        },
        {
          title: "操作",
          dataIndex: "serviceShowFile",
          key: "serviceShowFile",
          fixed: 'right',
          render: (text, render) => {
            return <div>
              <TheButton haspermi={['procurement:list:detail']}  onClick={()=>this.props.history.push('/procurement/details/'+render.id)}>查看详情</TheButton>
            </div>
          }
        },
      ],
      dataSource: [],
      newColumns: [],
      selectedKeys: { 1: [] },
      queryForm: {},
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
    }
  }

  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    
    let searchParams = store.getState().searchValue
    if (searchParams && searchParams.pathName === "procurementList") {
      let { pageNo, pageSize, queryForm, } = searchParams
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData()
      })
    } else {
      this.getData()
    }
  }

  getData = async function (values) {
    let { pageNo, pageSize } = this.state.pageData
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    },async ()=>{
      const params = {
        pageNo, pageSize, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'procurementList',
          ...params
        }
      })
      let res = await apiGetstockPurchasePage({
        pageNo, pageSize, ...this.state.queryForm
      })
      if(res.code === 0){
        this.setState({
          dataSource:res.data,
          total: res.totalCount,
        })
      }
    })
  }
  onColumnsFilter = (value) => {
    this.setState({
      newColumns: value
    })
  }

  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  } 

  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };

  onChange = (selectedRowKeys, selectedRows) => {
    let pageNo = this.state.pageData.pageNo
    let selectedKeys = { ...this.state.selectedKeys }
    selectedKeys[pageNo] = selectedRowKeys
    this.setState({
      selectedKeys
    }, () => {

    })
  }

  toExport = async () => {
    const { queryForm } = this.state
    let ids = ""
    Object.values(this.state.selectedKeys).forEach(value=>{
      ids += value.toString()+","
    })
    if(ids === ","){
      ids = ""
    }
    await apiStockPurchaseExport({ ...queryForm, ids}).then(res=>{
      if (res.code === 0 && res.data) {
        let th_arr = [
          {
            title: '采购单详情',
            prop: '',
            children: [
              {
                title: '序号',
                prop: 'index'
              },
              {
                title: '采购单号',
                prop: 'code'
              },
              {
                title: '供应商',
                prop: 'supplierName'
              },
              {
                title: '仓库',
                prop: 'libraryName'
              },
              {
                title: '创建人',
                prop: 'createUserName'
              },
              {
                title: '创建时间',
                prop: 'createTime'
              },
              {
                title: '订单状态',
                prop: 'status'
              },
              {
                title: '物品名称',
                prop: 'materialName',
              },
              {
                title: "物料ID",
                prop: "materialId",
              },
              {
                title: '规格',
                prop: 'skuName',
              },
              {
                title: '含税单价',
                prop: 'taxPrice',
                valueType:'number'
              },
              {
                title: '含税总价',
                prop: 'taxNumPrice',
                valueType:'number'
              },
              {
                title: '应收数量',
                prop: 'shouldInNum',
                valueType:'number'
              },
              {
                title: '实收数量',
                prop: 'realInNum',
                valueType:'number'
              },
            ]
          },
        ]
        let tb_arr = []
        res.data.forEach((item,index) => {
          let status = ""
          switch (item.status) {
            case 0:
              status="未完成"
              break;
            case 1:
              status="处理中"
              break;
            case 2:
              status="已完成"
              break;
            default:
              break;
          }
          item.stockPurchaseNoteDetailVos.forEach(item2 => {
            tb_arr.push({
              index: item.noteIndex,
              code: item.code || '/',
              supplierName: item.supplierName || '/',
              libraryName: item.libraryName || '/',
              createUserName: item.createUserName || '/',
              createTime: item.createTime || '/',
              status: status || '/',
              materialName: item2.materialName || '/',
              materialId: item2.materialId || '/',
              skuName: item2.skuName || '/',
              taxPrice: (item2.taxPrice/100).toFixed(2) || '/',
              taxNumPrice: (item2.taxNumPrice/100).toFixed(2) || '/',
              shouldInNum: item2.shouldInNum || '/',
              realInNum: item2.realInNum || '/',
            })
          })
        })
        const mergeProp = [
          'index',
          'code',
          'supplierName',
          'libraryName',
          'status',
          'createTime',
          'createUserName',
        ]
        exportSheetTable({ fileName: '采购单详情', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp })
        this.setState({
          selectedKeys:{1:[]}
        })
      }
    })
  }

  render() {
    const { searchOption, newColumns, dataSource, selectedKeys, pageData, total } = this.state
    const rowSelection = {
      selectedRowKeys: selectedKeys[pageData.pageNo],
      onChange: this.onChange,
    };
    return <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={newColumns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton hasPermi={['procurement:list:export']} size="middle" type="primary" onClick={() => this.toExport()}>导出</TheButton>
        </TheTableExtend>
        <TheTable columns={newColumns} dataSource={dataSource} pagination={false} bordered={1}
          scroll={{ x: 'max-content', y: '50vh' }}
          rowKey={record => record.id}
          rowSelection={rowSelection}
        ></TheTable>
        <ThePagination
          pageNo={pageData.pageNo}
          pageSize={pageData.pageSize}
          total={total}
          pageChange={this.pageChange}
        />
    </div>
  }

}

export default Procurement